#include "stdafx.h"
#include "ProcessManager.h"

CProcessManager* CProcessManager::m_pInstance = nullptr;

CProcessManager::CProcessManager()
{
}

CProcessManager::~CProcessManager()
{
}

//**********************************************************
//function:
bool CProcessManager::closeProcess(DWORD vProcessId)
{
    HANDLE ProcessHandle = OpenProcess(PROCESS_TERMINATE, FALSE, vProcessId);
    TerminateProcess(ProcessHandle, 0);
    return CloseHandle(ProcessHandle);
}

//**********************************************************
//function:
DWORD CProcessManager::getOrCreateProcess(const wchar_t* vPath, wchar_t* vCommandLine)
{
    wchar_t sep[] = L"\\";
    const wchar_t* name = wcsrchr(vPath, sep[0]) + 1;
    DWORD Id = getProcessIDByName(name);
    if (Id != (DWORD)INVALID_HANDLE_VALUE)
        return Id;
    STARTUPINFOW si = {};
    si.cb = sizeof(STARTUPINFOW);
    PROCESS_INFORMATION pi = {};
    if (CreateProcessW(
        vPath,
        vCommandLine,
        NULL,               
        NULL,               
        false,              
        0,					
        NULL,               
        NULL,               
        &si,                
        &pi                 
    ))
    {
        CloseHandle(pi.hProcess);
        CloseHandle(pi.hThread);
        return pi.dwProcessId;
    }
    else
    {
        return (DWORD)INVALID_HANDLE_VALUE;
    }
    return 0;
}

//**********************************************************
//function:
DWORD CProcessManager::getProcessIDByName(const wchar_t* vProcessName)
{
    HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (INVALID_HANDLE_VALUE == hProcessSnap) return (DWORD)INVALID_HANDLE_VALUE;

    PROCESSENTRY32 Process;
    Process.dwSize = sizeof(PROCESSENTRY32);
    DWORD ProcessID = (DWORD)INVALID_HANDLE_VALUE;
    for (BOOL p = Process32First(hProcessSnap, &Process); p; p = Process32Next(hProcessSnap, &Process))
    {
        if (_tcscmp(Process.szExeFile, vProcessName) == 0)
        {
            ProcessID = Process.th32ProcessID;
            break;
        }
    }
    CloseHandle(hProcessSnap);
    return ProcessID;
}
